<script lang='ts' setup>
import router from '@/router';
import type { LoginForm } from '@/api/user'
import { getAppInfo, login as loginReq } from "@/api/user"
import { ref } from 'vue';
import { getAndSaveUserInfo, handleLogin, logoutSystem } from '@/utils/user';
import { getMenuListData } from '@/permission';
import { getFirstRoute } from '@/utils/commonFunction'

const loginForm = ref<LoginForm>({
  account: '',
  password: ''
})
const rules = {
  account: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
  ]
}
const loginFormRef = ref()

function login() {
  loginFormRef.value.validate((valid: boolean) => {
    if (valid) {
      handleLogin(loginForm.value).then(async res => {
        try {
          await getMenuListData()
          let firstRoute = getFirstRoute()
          localStorage.setItem('firstRoutePath', firstRoute.path)
          await getAndSaveUserInfo()

          router.push(firstRoute.path)
        } catch (e) {
        }
      })
    }
  })
}

const backgroundUrl = ref('')
function hGetAppInfo() {
  getAppInfo().then(res => {
    document.title = res.data.name
    backgroundUrl.value = res.data.backgroundUrl
  })
}
hGetAppInfo()

</script>
<template>
  <div class="loginPage" :style="{ 'background-image': (backgroundUrl ? `url(${backgroundUrl}) !important` : '') }">
    <div class="loginBox">
      <h2>登录平台</h2>
      <el-form ref="loginFormRef" :model="loginForm" label-width="80px" :rules="rules" @submit.prevent>
        <el-form-item label="用户名" prop="account">
          <el-input placeholder="请输入用户名" v-model="loginForm.account" type="text" maxlength="20"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input placeholder="请输入密码" v-model="loginForm.password" type="password" maxlength="10"
            @keyup.enter="login"></el-input>
        </el-form-item>
      </el-form>
      <el-button type="primary" class="loginBtn" @click="login">登录</el-button>
    </div>
  </div>
</template>
<style scoped lang='scss'>
.loginPage {
  width: 100%;
  height: 100vh;
  position: fixed;
  top: 0;
  left: 0;
  background-image: url("../../assets/loginbg.png");
  background-size: cover;
}

.loginBox {
  width: 400px;
  margin: 0 auto;
  text-align: center;
  border: 1px solid #ccc;
  background: rgb(255, 255, 255, 0.3);
  backdrop-filter: blur(20px);
  padding: 30px;
  border-radius: 20px;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translateY(-50%) translateX(-50%);

  h2 {
    margin-bottom: 50px;
  }
}

.loginBtn {
  width: 100%;
  margin-top: 20px;
}
</style>